var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser'); //post数据
var logger = require('morgan');
const { errorCode, config, banIp } = require('./config/config');
const utils = require('./utils/utils.js');
var swagger = require('./utils/swagger'); // 使用swagger API 文档
const app = express();
const setLog = require("./utils/setLog");

// 及时通信
const expressWs = require('express-ws');
expressWs(app);

// 设置post 数据
// post最大数据100M
app.use(bodyParser.json({ limit: config.maxPostSize }));
app.use(bodyParser.urlencoded({ limit: config.maxPostSize, extended: false }));

let init = {
    devUrl: "http://" + utils.getIPAdress() + ":3001",
    FormalUrl: "/",
}
global.ip = init.FormalUrl;
if (config.development) {
    global.ip = init.devUrl;
}


// use swagger-Ui-express for your app documentation endpoint.
if (config.development) {
    swagger.swaggerInstall(app);
    swagger.swaggerInstallv2(app);
}

// use cookice
app.use(cookieParser());

/**设置跨域访问*/
if (config.crosEnable) {
    app.all(config.cors.origin, async (req, res, next) => {
        // 禁止访问的ip
        let ip = utils.getClientIP(req)
        if (banIp.indexOf(ip) != -1) {
            res.status(403);
            return res.send({
                ...errorCode[403]
            })
        }

        res.header("Access-Control-Allow-Origin", req.headers.origin); //需要显示设置来源，不能使用‘*’
        res.header("Access-Control-Allow-Headers", config.cors?.allowedHeaders || "Origin, X-Requested-With, Content-Type, Accept");
        res.header("Access-Control-Allow-Methods", config.cors?.methods || "PUT,POST,GET,DELETE,OPTIONS");
        res.header("Access-Control-Allow-Credentials", config.cors?.credentials || true); //需要加上这个
        res.header("Access-Control-Max-Age", config.cors?.maxAge || 86400);
        setLog(req, res);
        next();
    })
}

/**路由*/
const indexRouter = require('./routes/index.js');
const usersRouter = require('./routes/users.js');
const userApiRouter = require('./routes/userApi.js');
const adminApiRouter = require('./routes/adminApi.js');
const WeixinRouter = require("./routes/weixin"); //微信相关
const uploadRouter = require("./routes/uploadFile");
const biographicalNotesRouter = require('./routes/biographicalNotesApi.js'); // 个人简历
const emailRouter = require('./routes/emaliApi.js'); // 邮箱相关
const commentRouter = require('./routes/commentApi.js'); // 评论相关
const testRouter = require('./routes/test.js'); // 测试相关

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'upload')));
app.use(utils.checkReferer)

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/api/users", userApiRouter);
app.use("/api/v2/users" , require("./routes/v2/userApi"))
app.use("/api/admin", adminApiRouter);
app.use("/api/v2/admin", require("./routes/v2/adminApi"));
app.use("/api/weixin", WeixinRouter);
app.use("/api/upload", uploadRouter);
app.use("/api/biographicalNotes", biographicalNotesRouter);
app.use("/api/email", emailRouter);
app.use("/api/comment", commentRouter);
app.use("/api/test", testRouter);
app.use("/api/webChat", require("./routes/webChat"));
app.use("/api/v2/createFile", require("./routes/v2/createFile"));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    // next(createError(404));
    return res.send({
        ...errorCode[404]
    })
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    if (req.path.indexOf("/api") == 0) {
        return res.send({
            ...errorCode[err.status || 500]
        })
    }
    if (err.status == 404) {
        let Html404 = path.resolve(__dirname, "./public/404.html");
        return res.sendFile(Html404);
    }
    res.render('error');
});

module.exports = app;
